﻿#include <mosquitto.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{
	printf("主题：%s 内容：%s\n", msg->topic, (char *)msg->payload);
}

int main(void)
{
	struct mosquitto *mosq;
	int rc;
	//初始化mosquitto库
	mosquitto_lib_init();
	
	//创建客户端对象
	mosq = mosquitto_new(NULL, true, NULL);
	if(mosq == NULL){
		fprintf(stderr, "Error: Out of memory.\n");
		return -1;
	}
	
	//连接MQTT服务器
	rc = mosquitto_connect(mosq, "8.137.86.5", 1883, 60);
	if(rc != MOSQ_ERR_SUCCESS){
		mosquitto_destroy(mosq);
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
		return -1;
	}
	printf("连接MQTT服务器成功\n");

	rc = mosquitto_subscribe(mosq, NULL, "aaaa", 1);
	if(rc != MOSQ_ERR_SUCCESS){
		fprintf(stderr, "Error subscribing: %s\n", mosquitto_strerror(rc));
		/* We might as well disconnect if we were unable to subscribe */
		mosquitto_disconnect(mosq);
	}
	
	mosquitto_message_callback_set(mosq, on_message);

	mosquitto_loop_forever(mosq, -1, 1);

	
}

